import dayjs from "dayjs";
import editForm from "../form.vue";
import { handleTree } from "@/utils/tree";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
import { usePublicHooks } from "../../hooks";
import { transformI18n } from "@/plugins/i18n";
import { addDialog } from "@/components/ReDialog";
import type { FormItemProps } from "../utils/types";
import type { PaginationProps } from "@pureadmin/table";
import { getKeyList, deviceDetection } from "@pureadmin/utils";
import {
  getRoleList,
  getRoleMenu,
  getRoleMenuIds,
  updateRole,
  createRole,
  updateRoleMenu,
  deleteRole
} from "@/api/system";
import { type Ref, reactive, ref, onMounted, h, toRaw, watch } from "vue";

export function useRole(treeRef: Ref) {
  const form = reactive({
    name: "",
    key: "",
    status: ""
  });
  const curRow = ref();
  const formRef = ref();
  const dataList = ref([]);
  const treeIds = ref([]);
  const treeData = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const isLinkage = ref(true); // 默认启用父子联动
  const treeSearchValue = ref();
  const switchLoadMap = ref({});
  const isExpandAll = ref(false);
  const isSelectAll = ref(false);
  const { switchStyle } = usePublicHooks();
  const treeProps = {
    value: "ID",
    label: "title",
    children: "children"
  };
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "角色编号",
      prop: "ID"
    },
    {
      label: "角色名称",
      prop: "name"
    },
    {
      label: "角色标识",
      prop: "key"
    },
    {
      label: "状态",
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.status}
          active-value={1}
          inactive-value={0}
          active-text="已启用"
          inactive-text="已停用"
          inline-prompt
          style={switchStyle.value}
          onChange={() => onChange(scope as any)}
        />
      ),
      minWidth: 90
    },
    {
      label: "备注",
      prop: "remark",
      minWidth: 160
    },
    {
      label: "创建人",
      prop: "created_user.nickname"
    },
    {
      label: "创建时间",
      prop: "CreatedAt",
      minWidth: 160,
      formatter: ({ CreatedAt }) =>
        dayjs(CreatedAt).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      width: 210,
      slot: "operation"
    }
  ];
  // const buttonClass = computed(() => {
  //   return [
  //     "h-[20px]!",
  //     "reset-margin",
  //     "text-gray-500!",
  //     "dark:text-white!",
  //     "dark:hover:text-primary!"
  //   ];
  // });

  function onChange({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${
        row.status === 0 ? "停用" : "启用"
      }</strong><strong style='color:var(--el-color-primary)'>${
        row.name
      }</strong>吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(async () => {
        // 设置加载状态
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );

        try {
          // 调用启用/停用角色接口
          const newStatus = row.status;
          const response = await updateRole({
            id: row.ID,
            status: newStatus,
            name: row.name,
            remark: row.remark,
            key: row.key
          });

          // 请求成功处理
          if (response.success) {
            // 更新本地数据
            row.status = newStatus;
            message(`已${newStatus === 1 ? "启用" : "停用"}${row.name}`, {
              type: "success"
            });
          } else {
            message(`操作失败: ${response.msg || "未知错误"}`, {
              type: "error"
            });
            row.status = !newStatus; // 还原状态
          }
        } catch {
          // 请求失败处理
          row.status = row.status === 0 ? 1 : 0; // 状态还原
        } finally {
          // 无论成功失败，都关闭加载状态
          switchLoadMap.value[index] = Object.assign(
            {},
            switchLoadMap.value[index],
            {
              loading: false
            }
          );
        }
      })
      .catch(() => {
        row.status === 0 ? (row.status = 1) : (row.status = 0);
      });
  }

  async function handleDelete(row) {
    console.log(row.ID);
    try {
      const res = await deleteRole({
        ID: row.ID
      });
      if (res.success) {
        message(`您删除了角色名称为${row.name}的这条数据`, {
          type: "success"
        });
        onSearch();
      } else {
        message(res.msg, {
          type: "error"
        });
      }
    } catch (error) {
      message(error.message, {
        type: "error"
      });
    }
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  async function onSearch() {
    loading.value = true;
    const { data } = await getRoleList({
      ...toRaw(form),
      currentPage: pagination.currentPage, // 当前页码
      pageSize: pagination.pageSize // 每页条数
    });
    dataList.value = data.list || [];
    pagination.total = data.total || 0;
    // 只有当接口返回了有效的分页参数时才更新
    if (data.pageSize !== undefined) {
      pagination.pageSize = data.pageSize;
    }
    if (data.currentPage !== undefined) {
      pagination.currentPage = data.currentPage;
    }

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}角色`,
      props: {
        formInline: {
          id: row?.ID ?? 0,
          name: row?.name ?? "",
          key: row?.key ?? "",
          remark: row?.remark ?? "",
          status: row?.status ?? 1
        }
      },
      width: "40%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        FormRef.validate(valid => {
          if (valid) {
            console.log("curData", curData);
            // 表单规则校验通过
            if (title === "新增") {
              createRole(curData).then(res => {
                if (res.success) {
                  message(res.msg, {
                    type: "success"
                  });
                  done();
                  onSearch();
                } else {
                  message(res.msg, {
                    type: "error"
                  });
                }
              });
            } else {
              // 实际开发先调用修改接口，再进行下面操作
              updateRole(curData).then(res => {
                if (res.success) {
                  message(res.msg, {
                    type: "success"
                  });
                  done();
                  onSearch();
                } else {
                  message(res.msg, {
                    type: "error"
                  });
                }
              });
            }
          }
        });
      }
    });
  }

  /** 菜单权限 */
  // 存储初始选中状态
  const initialCheckedState = ref<{
    checkedKeys: string[];
    halfCheckedKeys: string[];
  }>({ checkedKeys: [], halfCheckedKeys: [] });

  async function handleMenu(row?: any) {
    const { ID } = row;
    if (ID) {
      curRow.value = row;
      isShow.value = true;
      const { data } = await getRoleMenuIds({ ID });
      treeRef.value.setCheckedKeys(data);
      // 等待tree组件更新后，获取所有选中的节点ID（包括自动选中的父节点）
      setTimeout(() => {
        initialCheckedState.value = {
          checkedKeys: [...treeRef.value.getCheckedKeys()], // 深拷贝确保不引用同一数组
          halfCheckedKeys: []
        };
      }, 0);
    } else {
      curRow.value = null;
      isShow.value = false;
      initialCheckedState.value = { checkedKeys: [], halfCheckedKeys: [] };
    }
  }

  /** 高亮当前权限选中行 */
  function rowStyle({ row: { ID } }) {
    return {
      cursor: "pointer",
      background: ID === curRow.value?.ID ? "var(--el-fill-color-light)" : ""
    };
  }

  /** 菜单权限-保存 */
  function handleSave() {
    const { ID, name } = curRow.value;
    // 获取选中的节点 ID 和半选中的父节点 ID
    const checkedKeys = treeRef.value.getCheckedKeys();
    const halfCheckedKeys = treeRef.value.getHalfCheckedKeys();

    // 检查菜单是否有变化（只比较checkedKeys，因为接口没有提供半选中状态的初始数据）
    const isChanged = !arraysEqual(
      checkedKeys,
      initialCheckedState.value.checkedKeys
    );

    if (!isChanged) {
      message("菜单权限没有变化，无需保存", {
        type: "info"
      });
      return;
    }

    // 合并所有相关的 ID
    const allRelatedIds = [...checkedKeys, ...halfCheckedKeys];
    // 根据用户 id 调用实际项目中菜单权限修改接口
    console.log(ID, allRelatedIds);
    updateRoleMenu({ ID, menuIds: allRelatedIds }).then(res => {
      if (res.success) {
        message(`角色名称为${name}的菜单权限修改成功`, {
          type: "success"
        });
        // 更新初始状态为当前状态（只更新checkedKeys）
        initialCheckedState.value = {
          checkedKeys: [...checkedKeys], // 深拷贝确保不引用同一数组
          halfCheckedKeys: []
        };
      } else {
        message(`操作失败: ${res.msg || "未知错误"}`, {
          type: "error"
        });
      }
    });
  }

  /** 比较两个数组是否相等 */
  function arraysEqual(arr1: any[], arr2: any[]): boolean {
    if (arr1.length !== arr2.length) return false;
    return arr1.every((value, index) => value === arr2[index]);
  }

  /** 数据权限 可自行开发 */
  // function handleDatabase() {}

  const onQueryChanged = (query: string) => {
    treeRef.value!.filter(query);
  };

  const filterMethod = (query: string, node) => {
    return transformI18n(node.title)!.includes(query);
  };

  onMounted(async () => {
    onSearch();
    const { data } = await getRoleMenu();
    treeIds.value = getKeyList(data, "ID");
    treeData.value = handleTree(data);
  });

  watch(isExpandAll, val => {
    val
      ? treeRef.value.setExpandedKeys(treeIds.value)
      : treeRef.value.setExpandedKeys([]);
  });

  watch(isSelectAll, val => {
    val
      ? treeRef.value.setCheckedKeys(treeIds.value)
      : treeRef.value.setCheckedKeys([]);
  });

  return {
    form,
    isShow,
    curRow,
    loading,
    columns,
    rowStyle,
    dataList,
    treeData,
    treeProps,
    isLinkage,
    pagination,
    isExpandAll,
    isSelectAll,
    treeSearchValue,
    // buttonClass,
    onSearch,
    resetForm,
    openDialog,
    handleMenu,
    handleSave,
    handleDelete,
    filterMethod,
    transformI18n,
    onQueryChanged,
    // handleDatabase,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange
  };
}
